
#include "Enemy/Enemy2D.h"

#include "PaperFlipbookComponent.h"
#include "Character/Character2D.h"
#include "Components/SphereComponent.h"
#include "Kismet/GameplayStatics.h"

AEnemy2D::AEnemy2D()
{
	PrimaryActorTick.bCanEverTick = true;

	SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComponent"));
	EnemyFlipbook = CreateDefaultSubobject<UPaperFlipbookComponent>(TEXT("EnemyFlipbook"));

	SetRootComponent(SphereComponent);
	EnemyFlipbook->SetupAttachment(RootComponent);
}

void AEnemy2D::BeginPlay()
{
	Super::BeginPlay();
}

void AEnemy2D::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (IsAlive && CanFollow && Player)
	{
		FVector CurrentLocation = GetActorLocation();
		FVector PlayerLocation = Player->GetActorLocation();

		FVector DirectionToPlayer = PlayerLocation - CurrentLocation;
		float DistanceToPlayer = DirectionToPlayer.Length();
		if (DistanceToPlayer >= StopDistance)
		{
			DirectionToPlayer.Normalize();
			FVector NewLocation = CurrentLocation + DirectionToPlayer * (MovementSpeed * DeltaTime);
			SetActorLocation(NewLocation);
		}
		
	}
	
}

void AEnemy2D::Die()
{
	if (!IsAlive) return;

	IsAlive = false;
	CanFollow = false;
	
	// EnemyFlipbook->SetFlipbook(HeadFlipbookAsset);
	// 半透明材质的渲染顺序。
	// EnemyFlipbook->SetTranslucentSortPriority(-5);

	
	EnemyFlipbook->Stop();
	EnemyFlipbook->SetSpriteColor(FLinearColor(0.2f, 0.2f, 0.2f, 1.0f));
	EnemyFlipbook->SetRelativeRotation(FRotator(0.0f, -90.0f, 90.0f));

	// SphereComponent->SetCollisionEnabled(ECollisionEnabled::NoCollision);
	
	// launchc
	SphereComponent->SetPhysicsLinearVelocity(FVector::UpVector * DieForce);
	
	float DestroyTime = 10.0f;
	GetWorldTimerManager().SetTimer(DestroyTimer, this, &AEnemy2D::OnDestroyTimerTimeout, 1.0f, false, DestroyTime);
}

void AEnemy2D::OnDestroyTimerTimeout()
{
	Destroy();
}

